// analyzeFormat.js
const fs = require('fs');
const path = require('path');
const { getAllFilesInDirectory } = require('../../../utils/fileUtils');

class FormatParser {
    async parse(dataset_info) {
        // console.log('vision detection format parser!');
        const dataset_dir = dataset_info.dataset_dir;

        // 判断是否是paddle格式标注
        let txtFiles = [];
        let txtFilePaths = await getAllFilesInDirectory(dataset_dir, ['.txt'], ['workspace']);
        // console.log(`txtFilePaths: `, txtFilePaths);
        for (let i = 0; i < txtFilePaths.length; i++) {
            let isPaddle = this.isPaddleFormat(txtFilePaths[i]);
            if (isPaddle) {
                const relativePath = path.relative(dataset_dir, txtFilePaths[i]);
                txtFiles.push(relativePath);
            }
        }
        return { code: 0, msg: { formats: ['paddle'], format: 'paddle', labels: txtFiles } };
    }

    isPaddleFormat(txtPath) {
        try {
            const txtData = fs.readFileSync(txtPath, 'utf8');
            const lines = txtData.trim().split('\n');
            // console.log('isPaddleFormat::lines = ', lines);

            // 检查每行是否符合PaddleOCR格式
            for (const line of lines) {
                if (!line.includes('\t')) {
                    return false;
                }

                const [imagePath, jsonStr] = line.split('\t');
                if (!imagePath || !jsonStr) {
                    return false;
                }
                // console.log(`imagePath: ${imagePath}, jsonStr: ${jsonStr}`);

                try {
                    const annotations = JSON.parse(jsonStr);

                    if (!Array.isArray(annotations)) {
                        return false;
                    }
                    for (const anno of annotations) {
                        if ((anno.transcription == undefined) || !anno.points ||
                            !Array.isArray(anno.points)) {
                            return false;
                        }
                    }
                } catch (e) {
                    console.log(`isPaddleFormat::error = `, e);
                    return false;
                }
            }
            return lines.length > 0;
        } catch (e) {
            return false;
        }
    }
}

module.exports = FormatParser;
